// vuex的状态机,根据功能模块划分为设备管理，设备点检，设备维修，设备保养等
import {
  downloadIdentify,
  fetchHistoryInfo,
  fetchList,
  fetchListInDevice,
  fetchBroadInfo,
  saveDeviceInfo,
  updateDeviceInfo,
  fetchDetailInfo,
  exportFile,
  downloadTemplete,
  deleteDeviceInfo,
  useInfo,
  uselessInfo
} from "@/api/device-basic/index";
import { reduceNullContent, deepClone } from "@/utils/index";
const state = {
  listSearchParams: {},
  lastSearchParams: {}, // 这个是导出时记载的上一次查询的条件，根据业务做的纪录保持
  paginationInfo: {},
  records: [], // 表格数据
  current: 1,
  pages: 1,
  total: 20,
  mesg: "",
  /**
   * 编辑相关
   */
  deviceBasicId: "",
  broadInfo: [], // 动态加载后端配置的扩展信息
  detailInfo: {}, // 详情模板
  totalForm: {},
  historyInfo: []
};
let formModel = {};
const mutations = {
  SET_LASTSEARCHPARAMS: (state, args) => {
    state.lastSearchParams = args;
  },
  SET_DEVICEBASICID: (state, args) => {
    state.deviceBasicId = args;
  },
  SET_LISTSERACH_PARAMS: (state, args) => {
    state.listSearchParams = args;
  },
  SET_LISTDATA: (state, args) => {
    state.records = args.records;
    state.pages = args.pages;
    state.current = args.current;
    state.total = args.total;
  },
  SET_BROAD_INFO: (state, args) => {
    state.totalForm[1].formComponent = args;
    state.totalForm[1].formModel = formModel;
  },
  SET_TOTAL_FORM: (state, args) => {
    state.totalForm = args;
  },
  SET_DETAIL_INFO: (state, args) => {
    state.detailInfo = args;
  },
  SET_PAGINATION: (state, args) => {
    state.paginationInfo = args;
  },
  SET_HISTORY: (state, args) => {
    state.historyInfo = args;
  }
};

const actions = {
  // 启用设备
  useDevice({ commit, state }, args) {
    return useInfo(reduceNullContent(args.id));
  },
  // 停用设备
  uselessDevice({ commit, state }, args) {
    return uselessInfo(reduceNullContent(args.id));
  },
  // 设置当前台账设备的id
  setDeviceBasicId({ commit, state }, args) {
    commit("SET_DEVICEBASICID", args);
  },
  // 设备台账查询参数
  setListSearchParams({ commit, state }, args) {
    const data = Object.assign({}, state.listSearchParams, args);
    commit("SET_LISTSERACH_PARAMS", data);
  },
  // 设备台账列表
  requestDeviceList({ commit, state }, args) {
    commit("SET_LASTSEARCHPARAMS", args);
    return fetchListInDevice(reduceNullContent(args)).then(response => {
      console.log("设备台账", response);
      commit("SET_LISTDATA", response.data);
    });
  },
  setTotalForm({ commit, state }, args) {
    console.log(args, "total");
    commit("SET_TOTAL_FORM", args);
  },
  // 保存设备台账
  saveDeviceInfo({ commit, state }, args) {
    // id存在为更新，否则为新增
    if (!args.id) {
      return saveDeviceInfo(args);
    } else {
      return updateDeviceInfo(args);
    }
  },
  // 设备台账单条数据的扩展信息模板请求
  requestDeviceBroadInfo({ commit, state }, args) {
    return fetchBroadInfo().then(response => {
      const array = response.data.map(e => {
        formModel[e.fieldName] = "";
        e.id = e.fieldName;
        e.type = e.fieldType; // e.fieldType == 1 ? "input" : "select"
        e.label = e.fieldName || "";
        e.format = e.fieldRuleType || "";
        // e.model = e.fieldCode
        e.rules = [
          { required: e.required, message: e.description, trigger: "blur" }
        ];
        e.model = e.fieldName;

        if (
          e.type == "input" ||
          e.type == "inputNumber" ||
          e.type == "inputFloat"
        ) {
          e.maxlength = e.fieldRuleType;
        }

        return e;
      });
      formModel = Object.assign({}, formModel, args);
      console.log("设备台账扩展信息", array);
      commit("SET_BROAD_INFO", array);

      // Just to simulate the time of the request
    });
  },
  // 设置设备台账对象
  setDetailInfo({ commit, state }, args) {
    commit("SET_DETAIL_INFO", args);
  },
  // 请求台账详情
  requestDeviceDetailInfo({ commit, state }, args) {
    commit("SET_DEVICEBASICID", args);
    return fetchDetailInfo(args).then(response => {
      console.log("设备台账详细信息", response);
      const data = {};
      data.detailInfo = state.detailInfo.detailInfo.map(item => {
        item.value = item.name ? response["data"][item.name] : "";
        return item;
      });
      data.createInfo = state.detailInfo.createInfo.map(item => {
        item.value = item.name ? response["data"][item.name] : "";
        return item;
      });
      data.drawPath = response["data"].drawPath;
      // 扩展字段特殊处理
      if (response["data"].extra) {
        const broadInfo = [];
        const broad = JSON.parse(response["data"].extra);
        for (const key in broad) {
          // data.broadInfo = state.detailInfo.broadInfo.map(item,i => {
          //     item.value = response["data"].extra ? JSON.parse(response["data"].extra)[item.name] : ""
          //     return item
          // })
          // data.broadInfo = state.detailInfo.broadInfo.map(item,i => {
          //     item.value = response["data"].extra ? JSON.parse(response["data"].extra)[item.name] : ""
          //     return item
          // })
          broadInfo.push({ value: broad[key], name: key, label: key });
          data.broadInfo = broadInfo;
        }
      }

      // data.histroyShowInfo=state.detailInfo.histroyShowInfo.map(item=>{
      //     item.value=state.detailInfo.detailInfo.archives
      //     return item
      // })
      commit("SET_DETAIL_INFO", data);

      // Just to simulate the time of the request
    });
  },
  // 编辑时请求单据详情
  requestDeviceEditInfo({ commit, state }, args) {
    commit("SET_DEVICEBASICID", args);
    return fetchDetailInfo(args).then(response => {
      console.log("设备台账详细信息", response.data);
      const data = response.data;

      return data;
    });
  },
  // 导出
  exportFile({ commit, state }, args) {
    console.log(state.lastSearchParams, "查询条件");
    console.log(args, "查询条件");
    // 这里根据产品业务要求进行导出的查询条件组装
    let data = {};
    if (args.length != 0) {
      // 有勾选条数
      const ids = args.map(item => item.id);
      console.log(ids, "选中参数");
      data.ids = ids;
    } else {
      // 无勾选时用上一次的查询条件
      data = state.lastSearchParams;
    }
    return exportFile(data);
  },

  // 下载导入模板
  async downloadTemplete({ commit, state }, args) {
    const data = {};
    data.objectName = "deviceTemplate.xls";
    data.expires = 3000;
    const res = await downloadTemplete(data);
    return res.data;
  },
  // 删除设备台账
  deleteDeviceInfo({ commit, state }, args) {
    return deleteDeviceInfo(args);
  },
  // 设置分页器
  setPagination({ commit, state }, args) {
    const data = {};
    data.sizeChange = args.sizeChange;
    data.currentChange = args.currentChange;
    data.current = state.current;
    data.total = state.total;
    commit("SET_PAGINATION", data);
  },
  // 下载标识卡
  downloadIdentify({ commit, state }, args) {
    return downloadIdentify(args);
  },

  // 获取档案信息
  historyInfo({ commit, state }, args) {
    return fetchHistoryInfo(args).then(response => {
      const words = [];
      const pdfs = [];
      const pictures = [];
      if (response.data.pdfs) {
        response.data.pdfs.map(item => {
          var data = {};
          data.imgSrc = item.viewPath;
          data.label = item.archiveName;
          data.download = item.archivePath;
          pdfs.push(data);
        });
      }
      if (response.data.words) {
        response.data.words.map(item => {
          var data = {};
          data.imgSrc = item.viewPath;
          data.label = item.archiveName;
          data.download = item.archivePath;
          words.push(data);
        });
      }
      if (response.data.pictures) {
        response.data.pictures.map(item => {
          var data = {};
          data.type = "img";
          data.imgSrc = item.viewPath;
          data.label = item.archiveName;
          data.download = item.archivePath;
          pictures.push(data);
        });
      }

      var historyInfo = [
        { label: "PDF", children: pdfs },
        { label: "WORD", children: words },
        { label: "PICTURE", children: pictures }
      ];
      commit("SET_HISTORY", historyInfo);

      // Just to simulate the time of the request
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
